package com.yaodian100.core.logger.service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.betwixt.expression.Context;
import org.apache.commons.betwixt.strategy.ObjectStringConverter;

public class CustomObjectStringConverter extends ObjectStringConverter implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1780546989307083136L;
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.UK);

	@Override
	public String objectToString(Object object, Class type, Context context) {
		if (object == null) {
			return null;
		}
		if (type == Date.class) {
			return dateFormat.format((Date) object);
		}
		if (type.getSuperclass() == Enum.class) {
			return object.toString();
		}
		return super.objectToString(object, type, context);
	}

	@Override
	public Object stringToObject(String string, Class type, Context context) {
		if (string == null || string.length() == 0) {
			return null;
		}
		if (type == BigDecimal.class) {
			return new BigDecimal(string).setScale(2);
		}
		if (type == Date.class) {
			return formatDate(string);
		}
		if (type.getName().equals("boolean")) {
			if ("true".equals(string))
				return true;
			else
				return false;
		}
		if (type.getName().equals("int")) {
			return Integer.parseInt(string);
		}
		if (type.getSuperclass() == Enum.class) {
			return Enum.valueOf(type, string);
		}
		return super.stringToObject(string, type, context);
	}

	protected Date formatDate(String string) {
		try {
			return dateFormat.parse(string);
		} catch (ParseException e) {
			throw new IllegalArgumentException(string, e);
		}
	}

}
